#main.py
#coding: utf-8
import sys, time
import os
import json

import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.options

from tornado.escape import json_decode
from tornado.options import options, define

from multiprocessing import Process, Queue

define ("port", default=8081, help="run on given port", type=int)

MsgQueue = Queue(1027)
MjpgStreamerCmd = 'mjpg_streamer -i "input_uvc.so -d /dev/video0 -r 800x600 -f 50" -o "output_http.so -w ./www_mjpeg -p 35080"&'

class WebCmdHandler(object):
    """docstring for WebCmdHandler"""
    local_url = "ipc:///tmp/web.ipc"
    drive_url = "ipc:///tmp/drive.ipc"
    servo_url = "ipc:///tmp/servo.ipc"
    router_url = "ipc:///tmp/router.ipc"
    # remote_urls = [drive_url, servo_url, router_url]
    remote_urls = [router_url]

    def __init__(self, queue):
        super(WebCmdHandler, self).__init__()
        self.queue = queue

    def handle(self, msg_s):
        print(type(msg_s), "-------web ipc send: ", msg_s)
        self.queue.put_nowait(msg_s)



msg_handler = WebCmdHandler(MsgQueue)

class SummaryHandler(tornado.web.RequestHandler):
    """docstring for SummaryHandler"""
    def get(self):
        header = self.request.headers
        user = header['User-Agent']
        # if -1 != header.find("Mac") or -1 != header.find("Windows"):
        if -1 != user.find("Android") or -1 != user.find("iPhone"):
            return self.render("dev_summary_m.html")

        return self.render("dev_summary.html")

    def post(self):
        print(self.request.remote_ip)
        msg_s = self.request.body.decode('utf-8')
        msg_handler.handle(msg_s)


class Application(tornado.web.Application):
    """docstring for Application"""
    def __init__(self):
        handlers = [
            (r"/", SummaryHandler),
            (r"/move", SummaryHandler)
        ]

        settings = {
            "template_path": "static",
            "static_path": "static",
            "debug": True
        }

        tornado.web.Application.__init__(self, handlers, **settings)

def start_mjpegstreamer():
    ret = os.system(MjpgStreamerCmd)
    if ret == 0:
        print("mjpg_streamer running...")
    else:
        print("camera init failed...")

def main():
    start_mjpegstreamer()

    tornado.options.parse_command_line()
    app = Application()

    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()    

if __name__ == '__main__':
    main()
